﻿#region Header

/*
Remote views based on linq
By

Pascal Hauser 
Dipl. Ing. in Informatik, Hochschule für Technik Rapperswil, 2006
Master Thesis, Hochschule für Technik Rapperswil, 2008-2010

and

Raphael Gfeller
Dipl. Ing. in Informatik, Hochschule für Technik Rapperswil, 2006
Master Thesis, Hochschule für Technik Rapperswil, 2008-2010

*/

#endregion

#region Usings

using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using Sebarf.Security.Interfaces;
using Utils;

#endregion

namespace Sebarf.Security.Authentication {
	/// <summary>
	/// authenticates the users based on
	///		args[PasswordMD5Hash] 
	/// and 
	///		a given collection of users
	/// <see cref="Users"/>
	/// </summary>
	public class UsernamePasswordAuthenticator : IAuthenticator {
		#region Public Properties

		/// <summary>
		/// Holds some users with their password hashes which can be authenticated.
		/// </summary>
		public ObservableCollection<User> Users { get; set; }

		#endregion

		#region Public Methods

		public UsernamePasswordAuthenticator() {
			Users = new ObservableCollection<User>();
		}

		#endregion

		#region private classes

		private class AuthenticatedUser : User, IIdentitity {
			#region IIdentitity Members

			public bool IsAuthenticated {
				get { return true; }
			}

			#endregion
		}

		#endregion

		#region IAuthenticator Members

		public IIdentitity Authenticate(DoAuthenticationRequest request) {
			IDictionary<string, object> args = request.AuthenticationArguments;
			if (!(args.ContainsKey("PasswordMD5Hash") && args.ContainsKey("Username"))) {
				return null;
			}
			string pawsswordHash = args["PasswordMD5Hash"].ToString();
			string id = args["Username"].ToString();

			AuthenticatedUser user = (from u in Users
									  where string.Equals(u.Id, id) && u.PasswordMd5Hash == pawsswordHash
									  select new AuthenticatedUser { Id = u.Id }).SingleOrDefault();
			return user;
		}

		#endregion
	}

	/// <summary>
	/// Represents a user that is identified by a id
	/// password is represented as md5 hash
	/// </summary>
	public class User : IIdentifiable {
		#region Public Properties

		public string PasswordMd5Hash { get; set; }

		#endregion

		#region IIdentifiable Members

		public string Id { get; set; }

		#endregion
	}
}